(function() {
    'use strict';

    const   childProcess = require('child_process'),
            util         = require('util'),
            events       = require('events');

    //ffmpeg -i h264.mp4 -c:v copy -bsf:v h264_mp4toannexb -an out.h264
    class H264Muxer extends events.EventEmitter {

        constructor(options) {
            super();

            this.url = options.url;
            this.cb  = options.cb;
            this.cberror = options.cberror;
            this.id =options.id;
            console.log("the id is %s",this.id);
            this.rtmp = "rtmp://"+options.tdcu + "/live/"+options.id;
            //console.log("url is "+this.url);
            this.stream = null;
        
            //this.pid = this.stream.pid;
            //this.inputStreamStarted = true;
    }
    closeMuxer(cb) {
        if (this.stream != null) {
            //this.stream.kill('SIGINT');
            this.stream.kill();
            if(cb!=null)
                cb("CLOSE");
        }
    }
    startMuxer(cb){

        console.log(this.url);
        this.stream = childProcess.spawn('ffmpeg', [
           '-loglevel', 'quiet',
            '-i', this.url
           , '-c:v', 'copy'
           //, '-vf', 'fps=25'
           , '-an' 
           //, '-b:v', '32k'
           , '-f','flv' 
           ,this.rtmp
        ]);
        //this.stream.stdout.setEncoding('utf8');
        //this.stream.stdout.on('data',function(data){
        //    console.log(data);
        //});
        //this.stream.stderr.setEncoding('utf8');
        //this.stream.stderr.on('data', function(data) {
        //   // console.log('stderr');
        //    console.log(data);
        //});

        this.stream.on('close', function (code, signal) {
            console.log("close");
            if(cb!=null)
            {
                console.log("close the id is %s",this.id);
                cb({item:this.id,mess:"CLOSE"});
            }
        });
        this.stream.on('error',function(code,signal){
            console.log("error");
             if(cb!=null){
                 cb({item:this.id,mess:"ERROR"});
            }
        });
    }
    
};

    module.exports = H264Muxer;
}());
